#!/usr/bin/env bash
set -o errexit
set -o nounset
set -o pipefail

if [ $# -lt 1 ]
then
  echo "usage: $0 FEATURE [OPTIONS]"
  exit 1
fi

feature=$1
shift

if [ ! -d target ]
then
  echo $0: 'Run `cargo check` first to prime the `target` directory.'
  exit 1
fi

target=$PWD/target-feature-$feature
log=$target/.logfile
trap 'rm --force --recursive $target' EXIT

cp --archive --link target $target
rm --force $target/debug/.cargo-lock

echo "===== Feature: $feature ====="
if cargo check --workspace --all-targets \
	--no-default-features \
	--features $feature \
	--target-dir $target \
	"$@" >$log 2>&1
then
  # If the run was successful, just output the `Finished` line
  # to prevent cluttering the logs.
  exit=0
  fgrep --word-regexp Finished $log
else
  exit=$?
  cat $log
fi

exit $exit

# It would be nice to relink newer files back into `target` so
# subsequent runs can pick them up, but that ends up confusing `cargo`
# later in the process.
